package com.durian.config;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.durian.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.sql.SQLException;
import java.util.Objects;

/**
 * 异常处理器
 *
 * @author Durian
 * @since 2023/11/27
 */
@RestControllerAdvice
public class ProjectExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(ProjectExceptionHandler.class);


    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("系统错误！", e);
        return Result.error("系统异常" + e.getMessage());
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                      HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return Result.error(e.getStatusCode().value() ,"不支持'" + e.getMethod() + "'方式的请求");
    }

    /**
     * 无法找到资源异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handleNoFoundException(NoHandlerFoundException e) {
        return Result.error(e.getStatusCode().value(), "没有找到资源");
    }

    /**
     * 参数类型匹配失败异常
     */
    @ExceptionHandler(TypeMismatchException.class)
    public Result handleTypeMismatchException() {
        return Result.error("参数类型匹配失败");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return Result.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public Result handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        Integer code = e.getCode();
        return ObjectUtils.isNotNull(code) ? Result.error(code, e.getMessage()) : Result.error(e.getMessage());
    }

    /**
     * SQL异常
     */
    @ExceptionHandler({BadSqlGrammarException.class, SQLException.class, DataIntegrityViolationException.class})
    public Result handleSQLSyntaxErrorException(BadSqlGrammarException e) {
        String message = e.getSQLException().getLocalizedMessage();
        return Result.error("SQL语句有误！" + message);
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder message = new StringBuilder();

        for (String s : Objects.requireNonNull(e.getDetailMessageArguments())[1].toString().split(",")) {
            String[] splitMsg = s.split("'");
            message.append(splitMsg[1]).append("  ");
        }
        return Result.error(e.getStatusCode().value(), message.toString().trim());
    }

}
